import axios from 'axios'
import { stringify } from 'qs'
import { useAuthStore } from '@/store/index'
import router from '@/router'
import { aesDecrypt, aesEncrypt } from '@/utils/crypto'

axios.defaults.timeout = 100000

axios.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore()
    const token = authStore.token
    if (token) {
      config.headers['Authorization'] = token
    }
    if (config.data && !config.headers['Content-Type']) {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      config.data = stringify(config.data)
    }

    if (!config._upload) {
      if (config.params) {
        config.params = { q: aesEncrypt(JSON.stringify(config.params)) }
      }
      if (config.data) {
        config.data = stringify({ d: aesEncrypt(config.data) })
      }
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

const listIdTrans = (list: any[]) => {
  list.forEach((o) => {
    if (o.id) {
      o.id = '' + o.id
    }
  })
}

axios.interceptors.response.use(
  (resp) => {
    const authStore = useAuthStore()
    const status = resp.status || 0
    const data = resp.data || {}
    if (status !== 200 || data.code !== 1000) {
      window._sgGlobal.$toast(data.msg || '操作失败')
      if (data.code === 1002) {
        authStore.logout()
        router.push({ name: 'login', query: { redirect: router.currentRoute.value.fullPath } })
      } else if (data.code === 999) {
        authStore.logout()
        router.push({ name: 'page-invalid', params: { invalidType: 'updating' } })
        return
      }
      return Promise.reject(resp)
    }

    if (data.apicrypt) {
      data.data = JSON.parse(aesDecrypt(data.data))
      if (data.data instanceof Array) {
        listIdTrans(data.data)
      } else if (data.data && data.data.list instanceof Array) {
        listIdTrans(data.data.list)
      }
    }

    return data
  },
  (error) => {
    window._sgGlobal.$toast(error || '操作失败')
    return Promise.reject(new Error(error))
  }
)

export default axios
